package cn.sinata.wanglin.property.activity;


import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.JsonObject;
import com.xilada.xldutils.activitys.CropImageActivity;
import com.xilada.xldutils.activitys.SelectPhotoDialog;
import com.xilada.xldutils.activitys.TitleActivity;
import com.xilada.xldutils.utils.ActivityUtil;
import com.xilada.xldutils.utils.SharedPreferencesUtils;
import com.xilada.xldutils.utils.Utils;
import com.xilada.xldutils.view.TwoTextLinearView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sinata.wanglin.MyApplication;
import cn.sinata.wanglin.R;
import cn.sinata.wanglin.aliyunoss.OssBean;
import cn.sinata.wanglin.aliyunoss.UpLoadImageUtils;
import cn.sinata.wanglin.commonutils.Constant;
import cn.sinata.wanglin.net.HttpManager;
import cn.sinata.wanglin.net.model.ResultData;
import cn.sinata.wanglin.net.model.util.ResultDataSubscriber;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;

/**
 * 业主认证页面
 */
public class OwnerCertificationActivity extends TitleActivity {
    @BindView(R.id.iv_upload_card)
    ImageView iv_upload_card;//照片显示
    @BindView(R.id.et_dong)
    EditText et_dong;//栋
    @BindView(R.id.et_danyuan)
    EditText et_danyuan;//单元
    @BindView(R.id.et_lou)
    EditText et_lou;//楼
    @BindView(R.id.et_hao)
    EditText et_hao;//号
    @BindView(R.id.tv_notice)
    TextView tv_notice;//文字提示
    @BindView(R.id.tv_searchvillage)
    TextView tv_searchvillage;//搜索小区文字显示
    @BindView(R.id.tv_choicevillage)
    TextView tv_choicevillage;//选择小区
    @BindView(R.id.tv_title_notice)
    TextView tv_title_notice;//选择小区文字提示

    @BindView(R.id.ttlv_mode)
    TwoTextLinearView ttlv_mode;//选择认证方式
    private String housingId=null;//小区ID
    private String housingName=null;//小区名字
    private  ArrayList<String> mItems;
    private  String currentMode="0";
    private String pathurl=null;//证件URL
    private int type=0;
    @Override
    protected int setContentId() {
        return R.layout.activity_ownercertification;
    }

    @Override
    protected void initView() {
        super.initView();
        setTitle("业主认证");
        addRightButton("提交审核", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //描述:提交审核
                surewithdrawals();
            }
        });
        Bundle mBundle=getIntent().getExtras();
        if(mBundle!=null){
            type= mBundle.getInt("type",0);
        }
        if(type==1){
            tv_searchvillage.setVisibility(View.VISIBLE);
            tv_choicevillage.setVisibility(View.GONE);
            tv_title_notice.setText("请选择你的小区");
        }else{
            tv_searchvillage.setVisibility(View.GONE);
            tv_choicevillage.setVisibility(View.VISIBLE);
            housingId=MyApplication.houseid;
            housingName=MyApplication.houseName;
            tv_choicevillage.setText(MyApplication.houseName);
            tv_title_notice.setText("认证小区");
        }
        mItems = new ArrayList<>();
        mItems.add("身份证");
        mItems.add("租赁合同");
        mItems.add("房产证");

    }
    /**
     * 修改认证方式
     */
    private void choiceMode() {

        OptionsPickerView pvOptions= new OptionsPickerView(this);
        pvOptions.setPicker(mItems);
        pvOptions.setTitle("选择认证方式");
        //设置数据是否循环
        pvOptions.setCyclic(false);
        //监听确定选择按钮
        pvOptions.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                currentMode=""+options1;
                ttlv_mode.setRightText(mItems.get(options1));
                pathurl="";
                iv_upload_card.setImageResource(R.mipmap.ic_uploadimg);
                switch (options1){
                    case 0:
                        tv_notice.setText("请上传身份证正面，照片清晰，内容完整");
                        break;
                    case 1:
                        tv_notice.setText("请上传租赁合同，照片清晰，内容完整");
                        break;
                    case 2:

                        tv_notice.setText("请上传房产证，照片清晰，内容完整");
                        break;
                }

            }
        });
        pvOptions.show();
    }

    @OnClick({ R.id.tv_searchvillage, R.id.ttlv_mode,R.id.iv_upload_card})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_searchvillage:
                //搜索小区
                ActivityUtil.create(mContext).go(SearchVillageActivity.class)
                        .startForResult(1);
                break;
            case R.id.ttlv_mode:
                //描述:选择上传方式
                choiceMode();
                break;
            case R.id.iv_upload_card:
                //描述:上传图片
                ActivityUtil.create(this).go(SelectPhotoDialog.class).startForResult(5);
                break;


        }
    }

    /**
     * 提交审核
     */
    private void surewithdrawals() {
        //小区判断
        if(TextUtils.isEmpty(housingId)){
            showToast("请选择小区！");
            return;
        }
        String dong= et_dong.getText().toString().trim();
        if(TextUtils.isEmpty(dong)){
            showToast("请先输入栋数！");
            return;
        }
        String danyuan= et_danyuan.getText().toString().trim();
        if(TextUtils.isEmpty(danyuan)){
            showToast("请先输入单元数！");
            return;
        }
        String lou= et_lou.getText().toString().trim();
        if(TextUtils.isEmpty(lou)){
            showToast("请先输入楼层数！");
            return;
        }
        String hao= et_hao.getText().toString().trim();
        if(TextUtils.isEmpty(hao)){
            showToast("请先输入门牌号！");
            return;
        }
        if(TextUtils.isEmpty(pathurl)){
            showToast("请选择证件照！");
            return;
        }
        String ownerType=null;
        if("2".equals(currentMode)){
            ownerType="0";//房主
        }else{
            ownerType="1";//租客
        }
        updateHead(pathurl,dong,danyuan,lou,hao,ownerType);

    }

    private void updateHead(final String path,final String dong,final String danyuan,final String lou,final String hao,final String ownerType){
        Utils.systemErr("-path-->"+path);
        final ArrayList<OssBean>  mOssBeans=new ArrayList<>();
        mOssBeans.add(new OssBean(path));
        Observable<List<OssBean>> mObservable= new UpLoadImageUtils(mOssBeans).uploadimg();
        mObservable.doOnSubscribe(new Action0() {
            @Override
            public void call() {
                showDialog("上传中...");
            }
        })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<OssBean>>() {
                    @Override
                    public void onCompleted() {
                        dismissDialog();
                    }
                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(List<OssBean> ossBeen) {
                        if(ossBeen!=null&&ossBeen.size()!=0){
                            houseAuthentication(housingId,dong,danyuan,lou,hao,currentMode,ownerType,ossBeen.get(0).getUrlkey(),"1.0");
                        }
                    }
                });


    }
   private  void houseAuthentication(String housingId,String building,
                        String unit,String floor,String doorNumber,
                        String authType,String ownerType,
                        String imgUrl,String scale){
       String userid= SharedPreferencesUtils.getString(Constant.SP_USERID);
       Observable<ResultData<JsonObject>> observable = HttpManager.houseAuthentication(userid,housingId,building,
                 unit,floor, doorNumber,
                authType, ownerType,
                imgUrl,scale);
       observable.subscribeOn(Schedulers.io())
               .doOnSubscribe(new Action0() {
                   @Override
                   public void call() {
                       showDialog();
                   }
               })
               .observeOn(AndroidSchedulers.mainThread())
               .subscribe(new ResultDataSubscriber<JsonObject>(this) {
                   @Override
                   public void onSuccess(String msg, JsonObject jsonObject) {
                       showToast(msg);
                       setResult(RESULT_OK);
                       finish();
                   }
               });

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK){
            switch (requestCode){
                case 1:
                    if(data!=null){
                        housingId=data.getStringExtra("housingId");
                        housingName=data.getStringExtra("housingName");
                        tv_searchvillage.setText(housingName);
                    }
                    break;

                case 6:
                    if (data!=null){
                        pathurl = data.getStringExtra("path");
                        iv_upload_card.setImageURI(Uri.parse("file://" + pathurl));
                    }
                    break;
                case 5:
                    if (data!=null){
                        String path = data.getStringExtra(SelectPhotoDialog.DATA);
                        cropImage(path);
                    }
                    break;


            }

        }
    }
    private void cropImage(String path){
        ActivityUtil.create(this).go(CropImageActivity.class)
                .put("uri",path)
                .put("mode",0)
                .startForResult(6);
    }
}
